package com.factory.code.service.impl;

import com.factory.code.controller.param.ConnectionParam;
import com.factory.code.controller.param.TableNameParam;
import com.factory.code.controller.vo.R;
import com.factory.code.lib.database.DatabaseBehaviorFactory;
import com.factory.code.lib.database.model.DatebaseTypeAndDriverModel;
import com.factory.code.lib.database.model.TableColumnModel;
import com.factory.code.lib.database.model.TableInfoModel;
import com.factory.code.service.DatabaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

@Service
@Slf4j
public class DatabaseServiceImpl implements DatabaseService {

    @Autowired
    private DatabaseBehaviorFactory databaseBehaviorFactory;

    @Override
    public boolean testConnection(ConnectionParam connectionParam) {
        Connection connection = null;
        try {
            Class.forName(connectionParam.getDbDriver());
            connection = DriverManager.getConnection(
                    connectionParam.getDbUrl(),
                    connectionParam.getDbUsername(),
                    connectionParam.getDbPassword());
            log.info("数据库验证通过 url={}", connectionParam.getDbUrl());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<String> listTableName(Integer projectId) {
        return databaseBehaviorFactory.getDatabaseBehavior(projectId).listTableName();
    }


    @Override
    public List<TableInfoModel> getTableAll(Integer projectId) {
        return databaseBehaviorFactory.getDatabaseBehavior(projectId).getTableAll();
    }

    @Override
    public List<TableColumnModel> listFieldModel(TableNameParam param) {
        return databaseBehaviorFactory.getDatabaseBehavior(param.getProjectId()).listFieldModel(param.getTableName());
    }


    @Override
    public List<DatebaseTypeAndDriverModel> listValidDbType() {
        return databaseBehaviorFactory.getTypeAndDriverList();
    }
}
